package zhaomh.zlogin;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.*;

public class PlayerData {
    private static final List<String> list = new ArrayList<>();
    private static final Map<String,Long> joinTimeMap = new HashMap<>();
    public static void addPlayer(Player player) {
        String name = player.getName();
        if (!list.contains(name)) {
            list.add(name);
        }
        System.out.println(list);
    }
    public static boolean isPlayerInList(Player player) {
        return list.contains(player.getName());
    }
    public static void removePlayer(Player player) {
        list.remove(player.getName());
    }
    public static void joinPlayer(Player player) {
        joinTimeMap.put(player.getName(),System.currentTimeMillis());
    }
    public static void initialize(){
        new BukkitRunnable() {
            @Override
            public void run() {
                try {
                    for (Map.Entry<String, Long> entry : joinTimeMap.entrySet()) {
                        String s = entry.getKey();
                        Long l = entry.getValue();
                        if (list.contains(s)) {
                            continue;
                        }
                        long time = System.currentTimeMillis();
                        if (time - l > Data.config.getInt("login.wait_time") * 1000L) {
                            Player player = Tools.getServer().getPlayer(s);
                            if (player != null)
                                Bukkit.getScheduler().scheduleSyncDelayedTask(Tools.getPlugin(), () -> {
                                    player.kickPlayer(Language.get("login.kick.timeout"));
                                    joinTimeMap.remove(s);
                                    removePlayer(player);
                                }, 1L);
                            joinTimeMap.remove(s);
                            if (player != null)
                                removePlayer(player);
                        }
                    }
                }catch (ConcurrentModificationException e) {
                    System.out.println("[Zlogin] error:-1");
                }
            }
        }.runTaskTimerAsynchronously(Tools.getPlugin(),0,20);
    }
}
